package org.guohao.mockdata.action;

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.guohao.mockdata.constant.DBType;
import org.guohao.mockdata.controller.ConnectController;
import org.guohao.mockdata.controller.HomeController;
import org.guohao.mockdata.utils.SyncManager;

public class NewConnectAction implements EventHandler<ActionEvent> {

  private final Stage mainStage;
  private final SyncManager syncManager;

  public NewConnectAction(Stage mainStage, SyncManager syncManager) {
    this.mainStage = mainStage;
    this.syncManager = syncManager;
  }

  @Override
  public void handle(ActionEvent actionEvent) {
    MenuItem menuItem = (MenuItem) actionEvent.getTarget();
    String dbTypeStr = menuItem.getText();
    DBType dbType = DBType.valueOf(dbTypeStr);
    Stage connectSetting = new Stage();
    FXMLLoader fxmlLoader = new FXMLLoader(
        HomeController.class.getResource("/fxml/connect.fxml"));
    Scene scene = null;
    try {
      scene = new Scene(fxmlLoader.load(), mainStage.getWidth() * 0.7,
          mainStage.getHeight() * 0.7);
    } catch (IOException e) {
      e.printStackTrace();
    }
    connectSetting.initOwner(mainStage);
    ConnectController controller = fxmlLoader.getController();
    controller.setSyncManager(syncManager);
    controller.dbType = dbType;
    controller.port.setText(dbType.getDefaultPort().toString());
    connectSetting.initModality(Modality.APPLICATION_MODAL);
    connectSetting.setTitle("新建连接-" + dbTypeStr);
    connectSetting.setScene(scene);
    connectSetting.show();
  }
}
